<?php
class FlowerOrderService {
    /**
     * @var FlowerOrderService
     */
    private static $instance;

    /**
     * Get the instance of FlowerOrderService.
     *
     * @return FlowerOrderService
     */
    public static function get() {
        if (!self::$instance) {
            self::$instance = new FlowerOrderService();
        }
        return self::$instance;
    }

    public function __construct() {

    }

    /**
     * 获取大额订单信息
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function flowerOrderInfo($userId,$reqTime) {
        /**
         * @var FlowerOrderVoList $flowerOrderList
         * @var FlowerOrderVo $flowerOrder
         */
        $flowerOrderList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FLOWER_ORDER);
        $flowerOrder = $flowerOrderList->getElement(GameConst::FLOWER_ORDER_PRIMARY_KEY,false);
        if (!$flowerOrder) {
            $flowerOrder = new FlowerOrderVo($userId,GameConst::FLOWER_ORDER_PRIMARY_KEY,[],[],0,0,0,$reqTime,true);
        }

        $refreshTime = $flowerOrder->getRefreshTime();

        $flowerMarketTime = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerMarkettime', true);
        $flowerMarketTime = json_decode($flowerMarketTime['value'],true);

        $len = count($flowerMarketTime);

        // 获取当前0点时间戳
        $todayTime = strtotime(date('Ymd',$reqTime));

        $startTime = $endTime = 0;
        for ($i=0;$i <= $len;$i++) {
            if ($i == 0) {
                $timeArr = array(
                    'startTime' => $todayTime - 3600 * (24 - $flowerMarketTime[$len - 1]),
                    'endTime' => $todayTime + 3600 * $flowerMarketTime[$i]
                );
            }else {
                $timeArr = array(
                    'startTime' => $todayTime + 3600 * $flowerMarketTime[$i - 1],
                    'endTime' => $todayTime + 3600 * ($flowerMarketTime[$i - 1] + $flowerMarketTime[$len - 1] - $flowerMarketTime[$len - 2])  ,
                );
            }

            if ($reqTime >= $timeArr['startTime'] && $reqTime < $timeArr['endTime']) {
                $startTime = $timeArr['startTime'];
                $endTime = $timeArr['endTime'];
            }
        }

        if ($refreshTime < $startTime || $refreshTime > $endTime) {
            $data = $this->getFlowerOrderInfo($userId);
            $targets = $data['targets'];
            $reward = $data['reward'];

            $flowerOrder->setTarget($targets);
            $flowerOrder->setReward($reward);
            $flowerOrder->setStatus(0);
            $flowerOrder->setRefreshTime($reqTime);
        }

        if (date('Ymd',$flowerOrder->getUpdateTime()) != date('Ymd',$reqTime)) {
            $flowerOrder->setRefreshTimes(0);
            $flowerOrder->setUpdateTime($reqTime);
        }

        if ( $flowerOrder->isInsert() && !SzUtility::checkArrayKey(GameConst::FLOWER_ORDER_PRIMARY_KEY, $flowerOrderList->getList())) {
            $flowerOrderList->addElement($flowerOrder);
            $flowerOrderList->setElement(GameConst::FLOWER_ORDER_PRIMARY_KEY,$flowerOrder);
        } else {
            $flowerOrderList->updateElement(GameConst::FLOWER_ORDER_PRIMARY_KEY, $flowerOrder);
        }

        SzPersister::get()->setVoList($flowerOrderList);
        return $flowerOrder->toArray();
    }

    /**
     * 刷新大额订单
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function refreshFlowerOrder($userId,$reqTime) {
        /**
         * @var FlowerOrderVoList $flowerOrderList
         * @var FlowerOrderVo $flowerOrder
         */
        $flowerOrderList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FLOWER_ORDER);
        $flowerOrder = $flowerOrderList->getElement(GameConst::FLOWER_ORDER_PRIMARY_KEY);

        $refreshTimes = $flowerOrder->getRefreshTimes();

        $updateTime = $flowerOrder->getUpdateTime();
        if (date('Ymd',$updateTime) != date('Ymd',$reqTime)) {
            $refreshTimes = 0;
        }

        $useGold = 0;

        if ($refreshTimes >= 1) {
            $flowerMarketRefresh = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerMarketRefresh', true);
            $flowerMarketRefresh = $flowerMarketRefresh['value'];
            GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $flowerMarketRefresh, true);
            CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_FLOWER_ORDER,$userId,0,GameConst::ENTITY_ACTION_CONSUME_MONEY.':'.$flowerMarketRefresh.'|','refreshFlowerOrder');//消耗资源上报
            $useGold = $flowerMarketRefresh;
        }

        $data = $this->getFlowerOrderInfo($userId);
        $targets = $data['targets'];
        $reward = $data['reward'];

        $refreshTimes++;
        $flowerOrder->setTarget($targets);
        $flowerOrder->setReward($reward);
        $flowerOrder->setRefreshTimes($refreshTimes);

        $flowerOrderList->updateElement(GameConst::FLOWER_ORDER_PRIMARY_KEY, $flowerOrder);
        SzPersister::get()->setVoList($flowerOrderList);

        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:fair|action:orderCD|',
                'item' => 'fair_orderCD',
                'value' => 1
            )
        ));

        if ($useGold) {
            StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
                'clientData' => array(
                    'item' => 'fair_orderCD',
                    'value' => $useGold
                )
            ));
        }


        return $flowerOrder->toArray();
    }

    /**
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function flowerOrderReward($userId,$reqTime) {
        /**
         * @var FlowerOrderVoList $flowerOrderList
         * @var FlowerOrderVo $flowerOrder
         */
        $flowerOrderList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FLOWER_ORDER);
        $flowerOrder = $flowerOrderList->getElement(GameConst::FLOWER_ORDER_PRIMARY_KEY);

        if (date('Ymd',$flowerOrder->getUpdateTime()) != date('Ymd',$reqTime)) {
            $flowerOrder->setRefreshTimes(0);
            $flowerOrder->setUpdateTime($reqTime);
        }

        if ($flowerOrder->getStatus()) {
            throw new SzException(90066);
        }

        $input = $output = '';
        foreach ($flowerOrder->getRawTarget() as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true, true);
            $input .= $entityId . ':' . abs($count) . '|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_FLOWER_ORDER,$userId,0,$input,'flowerOrderReward');//消耗资源上报

        $addition = 1;
        $orderBuffStatus = VideoService::get()->getBuffStatus($userId,GameConst::VIDEO_BUFF_ORDER,$reqTime);
        if ($orderBuffStatus) {
            $videoSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_VIDEO, GameConst::VIDEO_BUFF_ORDER, true);
            if ($videoSetting) {
                $addition = $videoSetting['sp_reward'][0];
            }
        }

        foreach ($flowerOrder->getRawReward() as $entityId => $count) {
            if ($orderBuffStatus && $entityId == GameConst::ENTITY_ACTION_GET_TOKEN) {
                $count = $count * $addition;
            }
            GameService::get()->handleEntity($userId, $entityId, $count, true, true);
            $output .= $entityId . ':' . abs($count) . '|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_FLOWER_ORDER,$userId,1,$output,'flowerOrderReward');//获得资源上报

        $flowerOrder->setStatus(1);

        $flowerOrderList->updateElement(GameConst::FLOWER_ORDER_PRIMARY_KEY, $flowerOrder);
        SzPersister::get()->setVoList($flowerOrderList);

        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:fair|action:order|',
                'item' => 'fair_order',
                'value' => 1
            )
        ));

        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' =>$output,
                'item' => 'fair_order',
            )
        ));

        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_INPUT, array(
            'clientData' => array(
                'tid' =>$input,
                'item' => 'fair_order',
            )
        ));

        TrainingService::get()->updateProgress($userId,GameConst::TRAINING_TASK_ORDER,1);

        // 更新合约任务进度
        $contractData = ContractService::get()->getContractOpenAndTask($userId,GameConst::CONTRACT_TASK_3,$reqTime);
        if (!empty($contractData) && !empty($contractData['task']) && !empty($contractData['session'])){
            if ($reqTime >= $contractData['start'] && $reqTime <= $contractData['end']){
                ContractService::get()->updateTaskProgress($userId,$contractData['session'],$contractData['task']['pos'],$contractData['task']['taskId'],$reqTime);
            }
        }

        //社团竞赛任务进度添加
        UnionCompetitionService::get()->addCompetitionTaskProcess($userId,GameConst::UNION_COMPETITION_TASK_6, $reqTime,1);

        return $flowerOrder->toArray();
    }

    /**
     * @param $userId
     * @return array
     * @throws SzException
     */
    public function getFlowerOrderInfo($userId) {
        $userLevel = UserService::get()->getUserLevel($userId);
        $flowerOrderSettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_FLOWER_ORDER, null, true);

        $quantity = 0;
        foreach ($flowerOrderSettings as $flowerOrderSetting) {
            list($min,$max) = $flowerOrderSetting['level'];
            if ($userLevel >= $min && $userLevel <= $max) {
                $quantity = $flowerOrderSetting['quantity'];
                break;
            }
        }

        $unlockFlowers = SeedService::get()->getUnlockFlowerList($userId);
        $key = array_rand($unlockFlowers);
        $flowerId = $unlockFlowers[$key];
        $buildEntityId = EntityService::get()->buildEntityId(GameConst::ENTITY_ACTION_CONSUME,GameConst::ENTITY_TYPE_ITEM,$flowerId);
        $targets = array(
            $buildEntityId => $quantity
        );

        $orderRewardSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_ORDER_REWARD, $flowerId, true);

        $flowerMarketExperience = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerMarketexperience', true);
        $flowerMarketExperience = $flowerMarketExperience['value'];

        $flowerMarketGold = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerMarketgold', true);
        $flowerMarketGold = $flowerMarketGold['value'];

        $goldNum = $orderRewardSetting['gold'];
        $experienceNum = $orderRewardSetting['experience'];
        $cashBuff = FlowersUpgradeService::get()->getFlowerBuff($userId,$flowerId,GameConst::FLOWER_TYPE_1);
        if (!empty($cashBuff)){
            if ($cashBuff[0] == 2){
                $goldNum = ($orderRewardSetting['gold'] + $cashBuff[1]);
            }
            if ($cashBuff[0] == 1){
                $goldNum = ceil($orderRewardSetting['gold']*(1+$cashBuff[1]/100));
            }
        }
        //20200409
        //获取玩家该花朵是否具有经验加成
        $experienceBuff = FlowersUpgradeService::get()->getFlowerBuff($userId,$flowerId,GameConst::FLOWER_TYPE_2);
        if (!empty($experienceBuff)){
            if ($experienceBuff[0] == 2){
                $experienceNum = ($orderRewardSetting['experience'] + $experienceBuff[1]);
            }
            if ($experienceBuff[0] == 1){
                $experienceNum = ceil($orderRewardSetting['experience']*(1+$experienceBuff[1]/100));
            }
        }

        $reward = array(
            GameConst::ENTITY_ACTION_GET_TOKEN => intval($goldNum*$quantity*(100+$flowerMarketGold)/100),
            GameConst::ENTITY_ACTION_GET_EXP => intval($experienceNum*$quantity*(100+$flowerMarketExperience)/100)
        );

        return array(
            'targets' => $targets,
            'reward' => $reward
        );
    }
}